In computer programming, a static variable is a variable that has been allocated statically — whose lifetime extends across the entire run of the program. This is in contrast to the more ephemeral automatic variables (local variables), whose storage is allocated and deallocated on the call stack; and in contrast to objects whose storage is dynamically allocated.
In many programming languages, such as Pascal, all local variables are automatic and all global variables are allocated statically. In these languages, the term "static variable" is generally not used, since "local" and "global" suffice to cover all the possibilities. Static variables are global, and in languages that do make the distinction between global and static variables, both are typically allocated without any distinction within the compiled code.
In the C programming language, the function of static variables can be illustrated as such:
#include <stdio.h> void func() { static int x = 0; // x is initialized only once across three calls of func() printf("%d\n", x); // outputs the value of x x = x + 1; } int main(int argc, char * const argv[]) { func(); // prints 0 func(); // prints 1 func(); // prints 2 return 0; }
In the C programming language (and its close descendants such as C++ and Objective-C), static
is a reserved word controlling both lifetime (as discussed above) and linkage (visibility). To be precise, static
is a storage class (not to be confused with classes in object-oriented programming), as are extern
, auto
and register
(which are also reserved words). Every variable and function has one of these storage classes; if a declaration does not specify the storage class, a context-dependent default is used (eg., extern
for all top-level declarations in a source file; auto
for variables declared in function bodies).
Storage class | Lifetime | Linkage |
---|---|---|
extern |
static | external (whole program) |
static |
static | internal (translation unit only) |
auto , register |
function call | (none) |
In these languages, the term "static variable" has two meanings which are easy to confuse:
static
Variables with storage class extern
, which include variables declared at top level without an explicit storage class, are "static" in the first meaning but not the second.
As well as specifying static lifetime, declaring a variable as static
can have other effects depending on where the declaration occurs:
static
at the top level of a source file (outside any function definitions) are only visible throughout that file ("file scope", also known as "internal linkage").static
inside a function are statically allocated while having the same scope as automatic local variables. Hence whatever values the function puts into its static local variables during one call will still be present when the function is called again.static
inside class definitions are class variables (shared between all class instances, as opposed to instance variables).